package cn.springcloud.fix.oauth.starter;

import com.alibaba.fastjson.JSON;
import com.maersk.common.core.base.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

	@Override
	public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
		response.setContentType("application/json;charset=utf-8");
		BaseResponse reslut;
		if (e instanceof BadCredentialsException || e instanceof UsernameNotFoundException) {
			reslut = BaseResponse.error(403, "账户名或者密码输入错误!");
		} else if (e instanceof LockedException) {
			reslut = BaseResponse.error(403, "账户被锁定，请联系管理员!");
		} else if (e instanceof CredentialsExpiredException) {
			reslut = BaseResponse.error(403, "密码过期，请联系管理员!");
		} else if (e instanceof AccountExpiredException) {
			reslut = BaseResponse.error(403, "账户过期，请联系管理员!");
		} else if (e instanceof DisabledException) {
			reslut = BaseResponse.error(403, "账户被禁用，请联系管理员!");
		} else {
			reslut = BaseResponse.error(403, "登录失败!");
		}
		response.setStatus(200);
		PrintWriter out = response.getWriter();
		out.print(JSON.toJSONString(reslut));
	}
}
